// 将token存储在vuex中，vuex刷新就没了，需要解决刷新就没了的问题
// import CookieJs from 'js-cookie'
import { getToken, setToken } from '@/utils/auth'
import { sysLogin } from '@/api/login'
import { sysProfile, sysUser } from '@/api/user.js'
import { Message } from 'element-ui'
import asyncRoutes from '@/router/modules/index.js'
import Router from '@/router'
import { constantRoutes, resetRouter } from '@/router'

const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout() {
    // mutations调用mutations
    // this===this.$store
    this.commit('user/setToken', '')
    this.commit('user/setUserInfo', '')
    // 重置路由
    resetRouter()
  }
}
const actions = {
  // 登录
  async toLogin(store, form) {
    const res = await sysLogin(form)
    Message.success('登录成功')
    store.commit('setToken', res.data)
  },
  // 获取用户信息
  async getUserInfo({ commit }) {
    const res = await sysProfile()
    // 获取用户头像
    const res2 = await sysUser(res.data.userId)
    // 合并对象  {a:1,obj:{xxx:2}}  {b:2} ===>  {a:1,b:2,obj:{xxx:1}}
    // 1：{...res,...res2} 2：返回值=Object.assign(目标对象，其它对象。。。。)
    // console.log('res2', res2)
    commit('setUserInfo', Object.assign({}, res.data, res2.data))
    // 匹配当前用户能访问的路由，通过addRoutes添加
    // 已知数据  res.data.roles.menus=['a']
    // 需要权限的路由
    // const arr = [
    //   { meta: { name: 'a' }},
    //   { meta: { name: 'b' }},
    //   { meta: { name: 'c' }}
    // ]
    // const arr2 = ['b']
    // const newArr = arr.filter((item) => {
    //   return arr2.includes(item.meta.name)
    // })
    // console.log('newArr', newArr)
    const newArr = asyncRoutes.filter((item) => {
      return res.data.roles.menus.includes(item.meta.name)
    })
    // addRoutes有一定小缺点，它刚添加的路由配制，需要再经过一次导航守卫后才可正常使用
    Router.addRoutes([...newArr, { path: '*', redirect: '/404', hidden: true }])
    // 拿到完整 路由信息  [静态路由，匹配到的动态路由，404匹配路由]
    const allRoutes = [
      ...constantRoutes,
      ...newArr,
      { path: '*', redirect: '/404', hidden: true }
    ]
    // 调用其它模块的mutations方法
    // commit('模块名/方法名',参数值,{root:true})
    commit('routes/setRoutesList', allRoutes, { root: true })

    console.log('newArr', newArr)
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
